package com.chinawlx.wlxteacher.ui.fragment.calendar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXRxBus;
import com.chinawlx.wlxteacher.ui.event.ShowClassEvent;
import com.chinawlx.wlxteacher.utils.WLXCalendarUtil;
import com.chinawlx.wlxteacher.utils.WLXConstant;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;

import com.chinawlx.wlxteacher.widget.calendar.WrapContentHeightGridView;

/**
 * 作者:吴名
 * 时间:16/9/3
 * 描述:日历-月份模式下的Fragment
 */
public class WLXMonthFragment extends Fragment {

    @BindView(R.id.tv_yearMonth)
    TextView mTvYearMonth;
    @BindView(R.id.grid_calendar)
    WrapContentHeightGridView mGrid;

    private int mYear;
    private int mMonth;
    private GridAdapter mGridAdapter;
    private Calendar mCalendar = Calendar.getInstance();
    /**
     * 某月1号对应GridView中的索引
     */
    private int mPos;
    private final ShowClassEvent mShowClassEvent = new ShowClassEvent();
    public static View mClickTvDay;//上一次点击的View(默认是今天)
    public static View mTodayView;//保留今天的View对象,便于改变背景

    private boolean isUpdate = false;//如果是更新Fragment,只更新单元格的课程状态,点击状态不更新

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {
        Bundle arguments = getArguments();

        if (arguments != null) {
            mYear = arguments.getInt("year");
            mMonth = arguments.getInt("month");
        }
        View view = inflater.inflate(R.layout.item_calendar_month, null);
        ButterKnife.bind(this, view);

        mTvYearMonth.setText(mYear + "年" + mMonth + "月");

        mCalendar.set(mYear, mMonth - 1, 1);
        mPos = mCalendar.get(Calendar.DAY_OF_WEEK) - 1;

        if (mGridAdapter == null) {
            mGridAdapter = new GridAdapter(getActivity());
            mGrid.setAdapter(mGridAdapter);
        } else {
            mGridAdapter.notifyDataSetChanged();
        }

        mGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                int differ = position - mPos;
                mCalendar.add(Calendar.DAY_OF_MONTH, differ);
                //是当月,点击才有反应
                if (mCalendar.get(Calendar.MONTH) == mMonth - 1) {
                    //改变被点击的单元格背景为蓝色圆圈,将今天的单元格换为黄色圆环
                    if (mClickTvDay != null && mTodayView != null && mClickTvDay == mTodayView) {
                        //上个点击的单元格是当天,就改为黄色圆圈
                        //noinspection deprecation
                        mClickTvDay.setBackgroundResource(R.drawable.shape_yellow_ring);
                    } else {
                        //不是当天,清除背景
                        //noinspection deprecation
                        mClickTvDay.setBackgroundDrawable(null);
                    }

                    //先把上次点击的背景换了之后,在改变点击的view
                    mClickTvDay = mGrid.getChildAt(position).findViewById(R.id.tv_day);
                    if (mTodayView != null && mClickTvDay == mTodayView) {//(mTodayView进去就赋值了,
                        // 不为空)点击的是今天
                        mClickTvDay.setBackgroundResource(R.drawable.shape_yellow_circle);
                    } else {
                        mClickTvDay.setBackgroundResource(R.drawable.shape_blue_circle);
                    }

                    //读取当天的课程信息,ListView显示课程列表
                    WLXConstant.date = mCalendar.getTimeInMillis() / (60 * 60 * 24 * 1000);
                    //当天日期换算成天数
                    WLXRxBus.getInstance().send(mShowClassEvent);
                }
                mCalendar.add(Calendar.DAY_OF_MONTH, -differ);//还原日期
            }
        });
        return view;
    }

    public static WLXMonthFragment newInstance(int year, int month) {
        WLXMonthFragment monthFragment = new WLXMonthFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("year", year);
        bundle.putInt("month", month);
        //Fragment保存参数,传入一个Bundle对象
        monthFragment.setArguments(bundle);
        return monthFragment;
    }

    public void update() {
        isUpdate = true;
        mGridAdapter.notifyDataSetChanged();
    }


    class GridAdapter extends BaseAdapter {
        private Context mContext;

        public GridAdapter(Context context) {
            this.mContext = context;
        }

        @Override
        public int getCount() {
            return 42;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ItemViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.item_calendar_day, null);
                holder = new ItemViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ItemViewHolder) convertView.getTag();
            }

            int differ = position - mPos;

            //===================begin=====因为算出来的日期得和初始值对比差值,所以用完之后得还原=======================
            mCalendar.add(Calendar.DAY_OF_MONTH, differ);
            int i = mCalendar.get(Calendar.DAY_OF_MONTH);

            TextView tvDay = holder.mTvDay;
            TextView tvClassCount = holder.mTvClassCount;

            //如果这个日期属于本月,字体为黑色,且有背景
            if (mCalendar.get(Calendar.MONTH) == mMonth - 1) {
                //noinspection deprecation
                tvDay.setTextColor(getResources().getColor(R.color.login_text_black));

                if (WLXCalendarUtil.isSameDay(mCalendar, WLXConstant.TODAY_CALENDAR)) {
                    //====================如果这一天等于今天========
                    mTodayView = tvDay;
                    if (isUpdate) {
                        //处于下拉刷新,且刷新前处于点击状态
                        if (mClickTvDay == tvDay) {
                            tvDay.setBackgroundResource(R.drawable.shape_yellow_circle);
                        } else {
                            //处于下拉刷新,刷新前不处于点击
                            tvDay.setBackgroundResource(R.drawable.shape_yellow_ring);
                        }
                    } else {
                        //不处于下拉刷新模式,背景为黄色圆,默认点击的今天
                        tvDay.setBackgroundResource(R.drawable.shape_yellow_circle);
                        mClickTvDay = tvDay;
                    }
                } else {
                    //====================如果这一天不等于今天=============
                    if (isUpdate) {
                        //处于下拉刷新,且刷新前处于点击状态
                        if (mClickTvDay == tvDay) {
                            tvDay.setBackgroundResource(R.drawable.shape_blue_circle);
                        } else {
                            //刷新前不处于点击
                            tvDay.setBackgroundDrawable(null);
                        }
                    } else {
                        //不处于刷新
                        tvDay.setBackgroundDrawable(null);
                    }
                }
            } else {
                //noinspection deprecation
                tvDay.setTextColor(getResources().getColor(R.color.gray_item));
            }


            //读取当天的课程信息,显示课程数量
            long key = mCalendar.getTimeInMillis() / (60 * 60 * 24 * 1000);//当天日期换算成天数
            if (WLXConstant.mSchedulehashMap.containsKey(key)) {
                //如果有key,说明这一天有课
                tvClassCount.setText(WLXConstant.mSchedulehashMap.get(key).size() + "");
                tvClassCount.setVisibility(View.VISIBLE);
            } else {
                //没课
                tvClassCount.setVisibility(View.GONE);
            }
            mCalendar.add(Calendar.DAY_OF_MONTH, -differ);
            //===================end===因为算出来的日期得和初始值对比差值,所以用完之后得还原=======================
            if (i < 10) {
                tvDay.setText("0" + i + "");
            } else {
                tvDay.setText(i + "");
            }
            return convertView;
        }


        class ItemViewHolder {
            @BindView(R.id.tv_day)
            TextView mTvDay;
            @BindView(R.id.tv_classCount)
            TextView mTvClassCount;

            ItemViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

}
